package com.jltx.xq.coroutinesandrxpro.flow

import androidx.lifecycle.*
import com.jltx.xq.coroutinesandrxpro.bean.Resource
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @author aidenquan
 *         Created by junlintianxia on 2021/08/12.
 */
class MainViewModel5 : ViewModel() {
    private val _myUiState = MutableStateFlow<Resource<String>>(Resource.Loading)
    val myUiState: StateFlow<Resource<String>> = _myUiState


    private val _myUiLiveData = MutableLiveData<Resource<String>>(Resource.Loading)
    val myUiLiveData: LiveData<Resource<String>> = _myUiLiveData

    /**
     * 原有的liveData方式回调到view
     */
    fun flowCreateRun() {
        viewModelScope.launch {
            FlowCreate.flowCreate().onStart {
                _myUiLiveData.postValue(Resource.Loading)
            }.flowOn(Dispatchers.IO).collect {
                if (_myUiLiveData.value?.isLoading == true) {
                    _myUiLiveData.value = Resource.Success("$it,")
                } else {
                    _myUiLiveData.value =
                        Resource.Success(_myUiLiveData.value?.valueOrNull + it.toString() + ",")
                }
            }
        }

    }

    /**
     * 第二种方式StateFlow返回
     */
    fun flowOfCreateRun() {
        viewModelScope.launch {
            FlowCreate.flowOfCreate().onStart {
                _myUiState.value = Resource.Loading
            }.flowOn(Dispatchers.IO).collect {
                if (_myUiState.value.isLoading) {
                    _myUiState.value = Resource.Success("$it,")
                } else {
                    _myUiState.value =
                        Resource.Success(_myUiState.value.valueOrNull + it.toString() + ",")
                }
            }
        }
    }


    fun asFlowCreateRun() {
        viewModelScope.launch {
            FlowCreate.asFlowCreate().onStart {
                _myUiState.value = Resource.Loading
            }.flowOn(Dispatchers.IO).collect {
                if (_myUiState.value.isLoading) {
                    _myUiState.value = Resource.Success("$it,")
                } else {
                    _myUiState.value =
                        Resource.Success(_myUiState.value.valueOrNull + it.toString() + ",")
                }
            }
        }
    }

    fun channelFlowCreateRun() {
        viewModelScope.launch {
            FlowCreate.channelFlowCreate().onStart {
                _myUiState.value = Resource.Loading
            }.onCompletion {
                println("Flow onCompletion end")
            }.flowOn(Dispatchers.IO).collect {
                println("Flow collect $it")
                if (_myUiState.value.isLoading) {
                    _myUiState.value = Resource.Success("$it,")
                } else {
                    _myUiState.value =
                        Resource.Success(_myUiState.value.valueOrNull + it.toString() + ",")
                }
            }
        }
    }
}